package com.umbrella.manage.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientService {
	private static Logger logger = LoggerFactory.getLogger(HttpClientService.class);

	/**
	 * @Description: POST 请求服务
	 * @author Liu, GuoBing @ 08/01/2018
	 * @param url
	 * @param requestData
	 * @return
	 */
	public static String doPost(String url, String requestData) {
		HttpClientBuilder httpClientBuilder = null;
		CloseableHttpClient closeableHttpClient = null;
		HttpPost httpPost = null;
		StringEntity entity;
		String result = "";
		try {
			httpClientBuilder = HttpClientBuilder.create();
			closeableHttpClient = httpClientBuilder.build();
			httpPost = new HttpPost(url);
			entity = new StringEntity(requestData, "utf-8");
			httpPost.setEntity(entity);
			HttpResponse httpResponse;
			httpResponse = closeableHttpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				result = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
			logger.error("request url:" + url + ", request data:" + requestData + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if (closeableHttpClient != null) {
					// 释放资源
					closeableHttpClient.close();
				}
			} catch (IOException e) {
				logger.error("request url:" + url + ", request data:" + requestData + e.getMessage());
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * GET 请求服务
	 * 
	 * @param url
	 * @param requestData
	 * @return
	 */
	public static String doGet(String url) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet httpPost = new HttpGet(url);
		String result = "";
		try {
			HttpResponse httpResponse;
			httpResponse = closeableHttpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				result = EntityUtils.toString(httpEntity, "UTF-8");
			}
		} catch (Exception e) {
			logger.error("request url:" + url + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				if (closeableHttpClient != null) {
					// 释放资源
					closeableHttpClient.close();
				}
			} catch (IOException e) {
				logger.error("request url:" + url + e.getMessage());
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param urlStr
	 *            请求的地址
	 * @param content
	 *            请求的参数 格式为：name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 * @param method
	 *            请求的方式。GET或者POST
	 * @return
	 */
	public static String getResult(String urlStr, String param, String encoding, String method) {
		String result = "";
		String line;
		StringBuffer sb = new StringBuffer();
		BufferedReader in = null;
		try {
			String urlNameString = urlStr + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性 设置请求格式
			conn.setRequestProperty("contentType", encoding);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// 设置超时时间
			conn.setConnectTimeout(120);
			conn.setReadTimeout(60);
			// 建立实际的连接
			conn.connect();
			// 定义 BufferedReader输入流来读取URL的响应,设置接收格式
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
}
